<template>
  <div style="padding: 20px;">
    <h2 style="margin-bottom: 20px;">{{ isEdit ? '编辑股票' : '新增股票' }}</h2>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="max-width: 600px;">
      <el-form-item label="股票代码" prop="code">
        <el-input v-model="form.code" placeholder="请输入股票代码"></el-input>
      </el-form-item>
      <el-form-item label="股票名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入股票名称"></el-input>
      </el-form-item>
      <el-form-item label="公司网址" prop="url">
        <el-input v-model="form.url" placeholder="请输入公司网址"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "StockForm",
  data() {
    return {
      form: {
        id: null,
        code: '',
        name: '',
        url: ''
      },
      rules: {
        code: [
          { required: true, message: '请输入股票代码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入股票名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        url: [
          { type: 'url', message: '请输入正确的网址格式', trigger: 'blur' }
        ]
      },
      isEdit: false,
      submitLoading: false
    }
  },
  created() {
    // 判断是编辑还是新增模式
    const id = this.$route.query.id;
    if (id) {
      this.isEdit = true;
      this.loadStockDetail(id);
    }
  },
  methods: {
    loadStockDetail(id) {
      this.request.get("/stock/" + id).then(res => {
        if (res.code === 200) {
          this.form = res.data;
        }
      }).catch(() => {
        this.$message.error('加载数据失败');
      });
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.request.post('/stock', this.form).then(res => {
            this.submitLoading = false;
            if (res.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '添加成功');
              this.$router.push({ name: 'Stock' });
            }
          }).catch(() => {
            this.submitLoading = false;
            this.$message.error('保存失败');
          });
        } else {
          this.$message.warning('请填写完整的表单信息');
          return false;
        }
      });
    },
    onCancel() {
      this.$router.push({ name: 'Stock' });
    }
  }
}
</script>

<style scoped>
</style>